use std::{
    fs::{self, File, OpenOptions},
    io::Write,
    path::Path,
};

use crate::types::TResult;

pub fn save_bytes_to_file(file_path: &str, buf: &[u8], auto_create: bool) -> TResult<()> {
    let mut file = match OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open(file_path)
    {
        Ok(file) => file,
        _ => {
            if !auto_create {
                return Err("文件不存在".into());
            }
            let path = Path::new(&file_path);
            let prefix = path.parent().ok_or("没有父级目录")?;
            fs::create_dir_all(prefix)?;
            File::create(file_path)?
        }
    };
    file.write_all(buf)?;
    Ok(())
}
